package com.feib.soeasy.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.RealAccount;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.RealAccountService;

/**
 * @title (#)Soez1001ActionBean.java <br>
 * @description 學雜費繳費 Controller<br>
 * @author Leo Lee
 * @version 1.0.0 2010/11/28
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/28 create by Leo Lee<br>
 */
public class Soez1001ActionBean extends BaseActionBean implements ValidationErrorHandler {

    /**
     * 學雜費繳費作業畫面
     */
    private static final String DEFAULT_JSP = "/WEB-INF/views/soez1001/soez1001.jsp";

    /**
     * 學雜費繳費清單畫面
     */
    private static final String PAYMENT_LIST_JSP = "/WEB-INF/views/soez1001/soez1001List.jsp";
    
    private static final String WEB_ATM_JSP = "/WEB-INF/views/soez1001/webAtm.jsp";
    /**
     * 檔案內容
     */
    private static final String AJAX_QUERY_PAYMENT_JSP = "/WEB-INF/views/soez1001/paymentList.jsp";
    /**
     * 業者代號查詢畫面
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez1001/groupPopUpList.jsp";
    
    /**
     * 帳單業者查詢條件
     */
    private Group qryGroup;
    

    private String groupNo;
    private String queryId;
    private String queryBirthday;//20110602 黃郁珊 增加增加生日檢核
  
	private Long paymentPk;
    private String fileMessage;
    

    @SpringBean("paymentService")
    private PaymentService paymentService;

    @SpringBean("groupService")
    private GroupService groupService;

    @SpringBean("realAccountService")
    private RealAccountService realAccountService;


    /**
     * 查詢結果
     */
    private PaginatedList<Payment> queryResult;
    
    /**
     * 查詢單筆Payment
     */
    private Payment resultPayment;
    
    /**
     * 線上繳款使用<br>
     * 線上繳款須用繳款單的繳費帳號前四碼做為帳單業者虛擬帳號，以找出實體帳號，取得 合作夥伴 公司代碼
     */
    private RealAccount realAccount;
    
    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;



    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {       
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP); 
    }

    /**
     * 查詢
     * @return
     */
    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {
        	if(groupNo==null||queryId==null||queryBirthday==null){
        		queryResult.setMessage("不可輸入空白!");
        	}else{
            Payment qryPayment = new Payment();
            Group group= new Group();  
            group.setGroupNo(groupNo);
            qryPayment.setGroup(group);
           
            queryResult = paymentService.queryByPayment(
                            qryPayment, null, null, queryResult, "P");
            if(queryResult.getFullListSize()>0){
            	qryPayment.setStudentId(queryId);
            	queryResult = paymentService.queryByPayment(
                        qryPayment, null, null, queryResult, "P");
            	if(queryResult.getFullListSize()>0){
            		 qryPayment.setPayerBirthday(queryBirthday);
            		 queryResult.setSortCriterion("virtualAccount");
                     queryResult.setSortDirection(1);           
                     queryResult.setPageSize(999);
                	 queryResult = paymentService.queryByPayment(
                            qryPayment, null, null, queryResult, "P");
                	if(queryResult.getFullListSize()==0){
                		queryResult.setMessage("生日錯誤");
                	}
                }else{
                	queryResult.setMessage("學號錯誤");
                }
            }else{
            	queryResult.setMessage("查無資料");
            }
        }
        }
        catch (Exception e) {
            logger.error("學雜費繳費查詢錯誤(Soez1001ActionBean.doAjaxQuery):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(PAYMENT_LIST_JSP);
    }
    
    public Resolution toWebAtm()
    {
        try {
            Payment payment = new Payment();
            payment.setPaymentPk(paymentPk);
            resultPayment = this.paymentService.getPaymentByPk(payment);
            
            if (null == resultPayment)
            {
                // 查無繳費單資料
            }
            else if (Payment.PAYMENT_STATUS_IN_PAYING.equals(resultPayment.getPaymentStatus()))
            {
                realAccount = new RealAccount();
                realAccount.setGroup(resultPayment.getGroup());
                realAccount.setVirtualAccountNo(resultPayment.getVirtualAccount().substring(0,4));
                realAccount = realAccountService.queryByGroupVirtualAccount(realAccount);
                if (null == realAccount)
                    throw new RuntimeException("查無作夥伴 公司代碼");
            }
            else
            {
                // 不用繳款
            }
            
            return new ForwardResolution(WEB_ATM_JSP);
            
        }
        catch (Exception e) {
            logger.error("學雜費繳費查詢錯誤(Soez1001ActionBean.toWebAtm):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }
    }

    public Resolution doDownloadPaymentAction()
    {

        //String pathName = "c:/temp/20101124144334.pdf";
        StreamingResolution streamingResolution = null;

        try {

            Payment payment = new Payment();
            payment.setPaymentPk(paymentPk);
            payment = paymentService.getPaymentByPk(payment);
            String pathName = payment.getPdfFilePathOnServer();
            File file = new File(pathName);

            byte[] bytes = new byte[(int)file.length()];

            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(file)); 
			
			bufferedInputStream.read(bytes);
			
			ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
			inputStream.close();
			bufferedInputStream.close();
			
            String isoFileName = new String(payment.getPdfFileName().getBytes(), "ISO8859-1");

            streamingResolution = new StreamingResolution( "application/pdf",inputStream).setFilename(isoFileName);
        } catch (Exception e) {
            logger.error("學雜費繳費下載錯誤(Soez1001ActionBean.doDownloadPaymentAction):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doDownloadPaymentAction.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }    	
        return streamingResolution;
    }

    public InputStream buildDowloadSource(String fileName)
    {
        try {
            InputStream inputStream = new FileInputStream(fileName);
            return inputStream;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 查詢轉入的帳單資料
     * @return
     */
    public Resolution doAjaxQueryFilePayments()
    {
        logger.debug("Enter doAjaxQueryFilePayments mehtod.");
        try {

            //呼叫服務查詢
            Payment qryPayment = new Payment();
            qryPayment.setPaymentPk(paymentPk);
            resultPayment = 
                paymentService.getPaymentByPk(qryPayment);
        }
        catch (Exception e) {
            logger.error("上傳記錄查詢-帳單內容查詢錯誤(Soez1017ActionBean.doAjaxQueryFilePayments):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_PAYMENT_JSP);
    }

    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {
            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //只查學校
            qryGroup.setGroupType(Group.GROUP_TYPE_SCHOOL);
            
            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("帳單明細資料下載-帳單業者查詢錯誤(Soez1018ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
    }


    public PaginatedList<Payment> getQueryResult() {
        return queryResult;
    }

    public void setQueryResult(PaginatedList<Payment> queryResult) {
        this.queryResult = queryResult;
    }


    public String getGroupNo() {
        return groupNo;
    }

    public void setGroupNo(String groupNo) {
        this.groupNo = groupNo;
    }

    public String getQueryId() {
        return queryId;
    }

    public void setQueryId(String queryId) {
        this.queryId = queryId;
    }
    public String getQueryBirthday() {
		return queryBirthday;
	}

	public void setQueryBirthday(String queryBirthday) {
		this.queryBirthday = queryBirthday;
	}

    public Long getPaymentPk() {
        return paymentPk;
    }

    public void setPaymentPk(Long paymentPk) {
        this.paymentPk = paymentPk;
    }

    public Payment getResultPayment() {
        return resultPayment;
    }

    public void setResultPayment(Payment resultPayment) {
        this.resultPayment = resultPayment;
    }

    public String getFileMessage() {
        return fileMessage;
    }

    public void setFileMessage(String fileMessage) {
        this.fileMessage = fileMessage;
    }

    public Group getQryGroup() {
        return qryGroup;
    }

    public void setQryGroup(Group qryGroup) {
        this.qryGroup = qryGroup;
    }

    public PaginatedList<Group> getQueryGroupResult() {
        return queryGroupResult;
    }

    public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
        this.queryGroupResult = queryGroupResult;
    }


    /**
     * @return the realAccount
     */
    public RealAccount getRealAccount() {
        return realAccount;
    }


    /**
     * @param realAccount the realAccount to set
     */
    public void setRealAccount(RealAccount realAccount) {
        this.realAccount = realAccount;
    }

}
